package com.dandev.cmdemo.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dandev.cmdemo.form.Communique;
import com.dandev.cmdemo.form.Contact;

@Repository
public class ContactDAOImpl implements ContactDAO {
	
	@Autowired
    private SessionFactory sessionFactory;


	public void addContact(Contact contact) {
		if(contact.getId() != null) {
			Contact oldContact = new Contact();
			oldContact.setId(contact.getId());
			sessionFactory.getCurrentSession().load(oldContact, oldContact.getId());
			oldContact.update(contact);
			sessionFactory.getCurrentSession().flush();
		} else {
			sessionFactory.getCurrentSession().save(contact);
		}
		
	}

	public List<Contact> listContact() {
		return sessionFactory.getCurrentSession().createQuery("from Contact where parent_id IS NULL").list();
	}
	
	public Contact getContact(Long id, boolean loadComm) {
		//Contact contact = (Contact) sessionFactory.getCurrentSession().load(Contact.class, id);
		//return contact;
		
		Contact contact = new Contact();
		contact.setId(id);
		//sessionFactory.getCurrentSession().update(contact);
		sessionFactory.getCurrentSession().load(contact, id);
		if(loadComm) {
			int temp = contact.getCommList().size();
		}
		return contact;
	}

	public void removeContact(Long id) {
		Contact contact = new Contact();
		contact.setId(id);
		sessionFactory.getCurrentSession().load(contact, id);
		if(contact.getContactList().size() == 0) {
			sessionFactory.getCurrentSession().delete(contact);
		}

	}
	
	public void addCommunique(Communique comm) {
		if(comm.getId() == null) {
			Contact contact = new Contact();
			contact.setId(comm.getParentContactId());
			sessionFactory.getCurrentSession().load(contact, comm.getParentContactId());
			contact.addCommunique(comm);
			comm.setParentContact(contact);
			sessionFactory.getCurrentSession().flush();
		} else {
			Communique oldComm = new Communique();
			oldComm.setId(comm.getId());
			sessionFactory.getCurrentSession().load(oldComm, oldComm.getId());
			oldComm.update(comm);
			sessionFactory.getCurrentSession().flush();
		}
	}
	
	public Communique getCommunique(Long id) {
		Communique comm = new Communique();
		comm.setId(id);
		sessionFactory.getCurrentSession().load(comm, id);
		comm.setParentContactId(comm.getParentContact().getId());
		//sessionFactory.getCurrentSession().flush();
		return comm;
	}
	
	public void removeCommunique(Long id) {
		Communique comm = new Communique();
		comm.setId(id);
		sessionFactory.getCurrentSession().load(comm, id);
		sessionFactory.getCurrentSession().delete(comm);
		
	}

}
